package com.easy.dn.ui.usercenter.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.easy.common.base.BaseActivity;
import com.easy.common.baseapp.AppManager;
import com.easy.common.baserx.RxBus;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonutils.ToastUitl;
import com.easy.common.commonwidget.RippleView;
import com.easy.dn.MainActivity;
import com.easy.dn.app.AppConstant;
import com.easy.dn.app.GlobalApplication;
import com.easy.dn.bean.UserInfoBean;
import com.easy.dn.ui.usercenter.contract.LoginContract;
import com.easy.dn.ui.usercenter.model.LoginModel;
import com.easy.dn.ui.usercenter.presenter.LoginPresenter;
import com.easy.dn.utils.CheckCode;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.encryption.RSACoder;
import com.easy.dn.widget.InputMethodRelativeLayout;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.qmuiteam.qmui.util.QMUIDirection;
import com.qmuiteam.qmui.util.QMUIViewHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import dn.easy.com.easyto.R;
import rx.Observable;
import rx.Observer;
/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * 登录
 *
 * @author DN
 * @data 2017/9/12
 **/
public class LoginActivity extends BaseActivity<LoginPresenter, LoginModel> implements LoginContract.View, InputMethodRelativeLayout.OnSizeChangedListenner, RippleView.OnRippleCompleteListener {


    @Bind(R.id.iv_img_backgroud)
    ImageView ivImgBackgroud;
    @Bind(R.id.de_frm_backgroud)
    FrameLayout deFrmBackgroud;
    @Bind(R.id.logoImg)
    ImageView mLogoImg;
    @Bind(R.id.country)
    TextView country;
    @Bind(R.id.loginCountryName)
    TextView loginCountryName;
    @Bind(R.id.loginCountryCode)
    Spinner loginCountryCode;
    @Bind(R.id.codeValue)
    TextView codeValue;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.userName)
    EditText userName;
    @Bind(R.id.usercenterPassword)
    TextView usercenterPassword;
    @Bind(R.id.pass)
    EditText pass;
    @Bind(R.id.VerifyPassword)
    TextView VerifyPassword;
    @Bind(R.id.password_once)
    EditText passwordOnce;
    @Bind(R.id.forgetBtn)
    RippleView forgetBtn;
    @Bind(R.id.okBtn)
    RippleView okBtn;
    @Bind(R.id.registerBtn)
    RippleView registerBtn;
    @Bind(R.id.scroll)
    ScrollView scroll;
    @Bind(R.id.loginlayout)
    InputMethodRelativeLayout loginlayout;
    @Bind(R.id.content)
    LinearLayout mContent;
    @Bind(R.id.ll_country)
    LinearLayout mCountryLinear;
    @Bind(R.id.positionLiear)
    TextView mPositionLiear;

    @Override
    public int getLayoutId() {
        return R.layout.act_login;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        okBtn.setOnRippleCompleteListener(this);
        registerBtn.setOnRippleCompleteListener(this);
        loginlayout.setOnSizeChangedListenner(this);

        /**
         * 周期性操作的操作符 get --> interval
         * MICROSECONDS    微秒   一百万分之一秒（就是毫秒/1000）
         * MICROSECONDS    微秒   一百万分之一秒（就是毫秒/1000）
         * MILLISECONDS    毫秒   千分之一秒
         * NANOSECONDS   毫微秒  十亿分之一秒（就是微秒/1000）
         * SECONDS          秒
         * MINUTES     分钟
         * HOURS      小时
         * DAYS      天
         */
        Observable.interval(20, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Long number) {
                        Animation animation = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.translate_anim);
                        ivImgBackgroud.startAnimation(animation);
                    }
                });
        //记录上次登录的手机号 对用户有好一点
        if (!StringUtils.isEmpty(SPUtils.getSharedStringData(mContext,AppConstant.LOGINPHONE)))
            userName.setText(SPUtils.getSharedStringData(mContext,AppConstant.LOGINPHONE));
    }





    @Override
    public void returnUserInfoData(UserInfoBean bean) {
        ToastUitl.showShort(R.string.login_success);
        GlobalApplication.getInstance().setAccessToken(bean.getAccess_token());
        GlobalApplication.getInstance().setRefreshToken(bean.getRefresh_token());
        GlobalApplication.getInstance().setUserID(bean.getUser().getId() + "");
        GlobalApplication.getInstance().setLogin(true);
        GlobalApplication.getInstance().setUserModel(bean.getUser());
        SPUtils.setSharedStringData(mContext,AppConstant.LOGINPHONE,userName.getText().toString().trim());
        //刷新个人中心 rxbus  现在测试 以后没有啥用 --。
        RxBus.getInstance().post(AppConstant.USERCENTERREFRESH, "ISFRESH");
        try {
            EMClient.getInstance().login(bean.getUser().getImusername(),
                    "111111", new EMCallBack() {
                        @Override
                        public void onSuccess() {

                            // ** 第一次登录或者之前logout后再登录,加载所有本地群和回话
                            // ** manually load all local groups and
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();    
                            Log.i("Dnlog","Success");

                            /**
                             *
                             *  回退管理  b并不完善
                             *   之前应该进入到哪个界面 就回到哪个界面并且刷新
                             */
                            if (AppManager.getAppManager().preActivity() != null) {
                                AppManager.getAppManager().preActivity().finish();
                                startActivity(AppManager.getAppManager().preActivity().getClass());
                                finish();
                            } else {
                                startActivity(MainActivity.class);
                                finish();
                            }
                        }

                        @Override
                        public void onError(int i, String s) {
                            Log.i("Dnlog",s+"");
                        }

                        @Override
                        public void onProgress(int i, String s) {
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showLoading(String title) {
    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AppManager.getAppManager().finishAllActivity();
    }

    @Override
    public void showErrorTip(String msg) {
//        ToastUitl.showShort(msg);
        DnUtils.showToast(okBtn, msg);
    }


    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.okBtn:
                login();
                break;
            case R.id.registerBtn:
                startActivity(RegisterActivity.class);
                break;
        }
    }

    private void login() {
        if (CheckCode.isNumeric(userName.getText().toString()) && userName.getText().toString().trim().length() > 0) {
            if (pass.getText().toString().trim().length() > 0) {
                Map<String, String> map = new HashMap<String, String>();
                try {
                    map.put("phone", userName.getText().toString());
                    map.put("clientType", "Android");
                    map.put("areaCode", "");
                    map.put("password", RSACoder.encrypt(pass.getText().toString()));
                    mPresenter.getUserInfoData(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUitl.showShort(R.string.login_fail);
                }

            } else {
                ToastUitl.showShort(R.string.write_pass);
            }
        } else {
            ToastUitl.showShort(R.string.write_phone);
        }
    }

    @OnClick({R.id.ll_country, R.id.content})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_country:
                //国家
                break;
            case R.id.content:
                break;
        }
    }

    @Override
    public void onSizeChange(boolean paramBoolean, int w, int h) {
        if (paramBoolean) {// 键盘弹出时
//            mPositionLiear.setVisibility(View.GONE);
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", 0.0f, -10);
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
            mAnimatorTranslateY.start();
            zoomIn(mLogoImg, 0.6f, 10);
            QMUIViewHelper.slideOut(mPositionLiear, 100, null, true, QMUIDirection.BOTTOM_TO_TOP);
        } else { // 键盘隐藏时
//            mPositionLiear.setVisibility(View.VISIBLE);
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", mContent.getTranslationY(), 0);
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
            mAnimatorTranslateY.start();
            //键盘收回后，logo恢复原来大小，位置同样回到初始位置
            zoomOut(mLogoImg, 0.6f);
            QMUIViewHelper.slideIn(mPositionLiear, 100, null, true, QMUIDirection.TOP_TO_BOTTOM);

        }
    }

    /**
     * 缩小
     *
     * @param view
     */
    public static void zoomIn(final View view, float scale, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    /**
     * f放大
     *
     * @param view
     */
    public static void zoomOut(final View view, float scale) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }
}
